<template>
  <div class="kpi-devired">
    <div class="bussiness-list">
      <el-collapse v-model="type" accordion>
        <el-collapse-item name="all" title="全部字段">
          <template v-if="fieldList.length">
            <el-input v-model="keyword" placeholder="搜索字段" clearable></el-input>
            <ul class="field-list tag-scrollbar">
              <li v-for="item in showFieldList" :key="item.fieldNm" draggable @dragstart="copyDrag($event, item)">
                {{ item.fieldNm }}
                <div class="list-handler">
                  <el-tooltip effect="dark" content="添加" placement="top" :enterable="false">
                    <span class="plus" @click.prevent="addItem(item)"><i class="el-icon-plus"></i></span>
                  </el-tooltip>
                </div>
              </li>
            </ul>
          </template>
          <div class="no-record" v-else>
            <template v-if="selectTable">
              <img src="~@/assets/img/no_records.png" /><br />
              暂无内容
            </template>
            <template v-else>
              请先选择原子指标
            </template>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <div class="devired-content" v-loading="loading">
      <div class="header">
        <el-row :gutter="20">
          <el-col :span="6" align="left">
            <div class="factory-top">
              <icon-svg name="iconCalculate"></icon-svg>
              衍生指标
            </div>
          </el-col>
          <el-col :span="18" align="right">
            <div class="btns">
              <el-button @click="handleReject">
                <icon-svg name="iconCancel"></icon-svg>
                取消
              </el-button>
              <el-button type="primary" @click="handlePreview">
                <icon-svg name="iconFacEye"></icon-svg>
                预览
              </el-button>
              <el-button type="primary" @click="handleSave">
                <icon-svg name="iconSave"></icon-svg>
                保存
              </el-button>
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="content tag-scrollbar">
        <div class="section-title">
          <i :class="showCinfig ? 'el-icon-caret-bottom' : 'el-icon-caret-right'" @click="showCinfig = !showCinfig"></i>
          指标配置
        </div>
        <el-collapse-transition>
          <div class="section-content" v-show="showCinfig">
            <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="0">
              <el-row :gutter="20">
                <el-col :span="6">
                  <div class="source-item">
                    <div class="star"></div>
                    <div class="source-title linear-purpose">原子指标</div>
                    <div class="source-content">
                      <el-form-item prop="atomicId">
                        <el-select v-model="editForm.atomicId" filterable clearable @change="changeAtom">
                          <el-option label="---" value=""></el-option>
                          <el-option
                            v-for="item in atomList"
                            :key="item.tagId"
                            :label="item.tagNm"
                            :value="item.tagId"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </div>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="source-item">
                    <div class="source-title linear-purpose">维度</div>
                    <div class="source-content">
                      <el-form-item prop="dimensionId">
                        <el-select v-model="editForm.dimensionId" filterable clearable>
                          <el-option label="---" value=""></el-option>
                          <el-option
                            v-for="item in dimensionList"
                            :key="item.tagId"
                            :label="showNm(item, 'dimensionName')"
                            :value="item.tagId"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </div>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="source-item">
                    <div class="source-title linear-purpose">时间修饰词</div>
                    <div class="source-content">
                      <el-form-item prop="timeModifiersId">
                        <el-select v-model="editForm.timeModifiersId" filterable clearable>
                          <el-option label="---" value=""></el-option>
                          <el-option
                            v-for="item in timeList"
                            :key="item.tagId"
                            :label="showNm(item, 'timeModificationName')"
                            :value="item.tagId"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </div>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="source-item">
                    <div class="source-title linear-purpose">时间映射字段</div>
                    <div class="source-content">
                      <el-form-item prop="timeColumn">
                        <el-select v-model="editForm.timeColumn" filterable clearable>
                          <el-option label="---" value=""></el-option>
                          <el-option v-for="item in timeColumnList" :key="item" :label="item" :value="item"></el-option>
                        </el-select>
                      </el-form-item>
                    </div>
                  </div>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="6">
                  <div class="source-item">
                    <div class="source-title linear-cyan">业务修饰词</div>
                    <div class="source-content">
                      <el-form-item prop="businessType">
                        <el-radio-group v-model="editForm.businessType">
                          <el-radio label="quick">快速选择</el-radio>
                          <el-radio label="diy">自定义</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </div>
                  </div>
                </el-col>
                <el-col :span="6" v-if="editForm.businessType === 'quick'">
                  <div class="source-item">
                    <div class="source-title linear-cyan" style="padding-left: 35px">选择业务修饰词</div>
                    <div class="source-content">
                      <el-form-item prop="businessModifiersId">
                        <el-select v-model="editForm.businessModifiersId" filterable clearable>
                          <el-option label="---" value=""></el-option>
                          <el-option
                            v-for="item in bussinessList"
                            :key="item.tagId"
                            :label="showNm(item, 'businessName')"
                            :value="item.tagId"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </div>
                  </div>
                </el-col>
                <el-col :span="6" v-if="editForm.businessType === 'diy'">
                  <div class="source-item">
                    <div class="source-title linear-cyan">修饰词名称</div>
                    <div class="source-content">
                      <el-form-item
                        prop="businessModifiersName"
                        :rules="
                          editForm.tagConfig.tagList.length
                            ? { required: true, message: '自定义业务修饰词名称不能为空', trigger: 'change' }
                            : []
                        "
                      >
                        <el-input
                          v-model="editForm.businessModifiersName"
                          placeholder="请输入自定义业务修饰词名称"
                        ></el-input>
                      </el-form-item>
                    </div>
                  </div>
                </el-col>
              </el-row>
              <div
                class="list-wrap"
                @drop="copyDrop($event)"
                @dragover="allowDrag($event)"
                v-if="editForm.businessType === 'diy'"
              >
                <div class="config-tips" v-if="!editForm.tagConfig.tagList.length">
                  <span>
                    <i class="el-icon-plus"></i>
                  </span>
                  <br />
                  将字段拖入此区域，添加业务修饰词配置
                </div>
                <div class="ul" v-else>
                  <div
                    class="logical"
                    :class="{ 'logical-or': editForm.tagConfig.logicalOperation === 'or' }"
                    v-if="editForm.tagConfig.tagList.length > 1"
                  >
                    <el-form-item prop="logicalOperation">
                      <el-select
                        v-model="editForm.tagConfig.logicalOperation"
                        @click.native="toggleOperation(-1)"
                        disabled
                        popper-class="factory-select"
                        class="default"
                      >
                        <el-option label="且" value="and"></el-option>
                        <el-option label="或" value="or"></el-option>
                      </el-select>
                    </el-form-item>
                  </div>
                  <div v-for="(item, index) in editForm.tagConfig.tagList" :key="index" class="ul-wrap">
                    <!-- 没有下级 -->
                    <template v-if="!item.tagList">
                      <div class="list-item" :level="1" :fieldNm="item.fieldNm" :index="index">
                        <el-row :gutter="8">
                          <el-col :span="8">
                            <div class="item" align="center" draggable @dragstart="copyDrag($event, item, index)">
                              {{ item.fieldNm }}
                            </div>
                          </el-col>
                          <el-col :span="4" align="center">
                            <div class="item">
                              <el-form-item
                                :prop="'tagConfig.tagList.' + index + '.operationType'"
                                :rules="[
                                  {
                                    required: true,
                                    message: '运算符不能为空',
                                    trigger: 'change'
                                  }
                                ]"
                              >
                                <el-select v-model="item.operationType" @change="changeType($event, item)">
                                  <el-option label="---" value=""></el-option>
                                  <el-option
                                    v-for="opera in operatorType('type' + item.valueType)"
                                    :key="opera.value"
                                    :label="opera.key"
                                    :value="opera.value"
                                  ></el-option>
                                </el-select>
                              </el-form-item>
                            </div>
                          </el-col>
                          <el-col :span="12">
                            <div class="item">
                              <el-form-item
                                :prop="'tagConfig.tagList.' + index + '.operationValue'"
                                :rules="[
                                  {
                                    required: true,
                                    message: '值不能为空',
                                    trigger: ['blur', 'change']
                                  }
                                ]"
                              >
                                <factory-content-item :config="item"></factory-content-item>
                              </el-form-item>
                            </div>
                          </el-col>
                        </el-row>
                        <el-button
                          type="primary"
                          size="mini"
                          icon="el-icon-close"
                          circle
                          @click="deleteItem(index)"
                        ></el-button>
                      </div>
                    </template>
                    <template v-else>
                      <div class="ol" :class="{ space: item.tagList.length > 1 }">
                        <div class="logical" :class="{ 'logical-or': item.logicalOperation === 'or' }">
                          <el-form-item :prop="'tagConfig.tagList.' + index + '.logicalOperation'">
                            <el-select
                              v-model="item.logicalOperation"
                              @click.native="toggleOperation(index)"
                              :level="index"
                              popper-class="factory-select"
                              disabled
                              class="default"
                            >
                              <el-option label="且" value="and"></el-option>
                              <el-option label="或" value="or"></el-option>
                            </el-select>
                          </el-form-item>
                        </div>
                        <div v-for="(child, index2) in item.tagList" :key="index2">
                          <!-- 没有第三层 -->
                          <template v-if="!child.tagList">
                            <div class="list-item" :level="2" :fieldNm="child.fieldNm" :index="index + '-' + index2">
                              <el-row :gutter="8">
                                <el-col :span="8">
                                  <div
                                    class="item"
                                    align="center"
                                    draggable
                                    @dragstart="copyDrag($event, child, index, index2)"
                                  >
                                    {{ child.fieldNm }}
                                  </div>
                                </el-col>
                                <el-col :span="4" align="center">
                                  <div class="item">
                                    <el-form-item
                                      :prop="'tagConfig.tagList.' + index + '.tagList.' + index2 + '.operationType'"
                                      :rules="[
                                        {
                                          required: true,
                                          message: '运算符不能为空',
                                          trigger: 'change'
                                        }
                                      ]"
                                    >
                                      <el-select v-model="child.operationType" @change="changeType($event, child)">
                                        <el-option label="---" value=""></el-option>
                                        <el-option
                                          v-for="opera in operatorType('type' + child.valueType)"
                                          :key="opera.value"
                                          :label="opera.key"
                                          :value="opera.value"
                                        ></el-option>
                                      </el-select>
                                    </el-form-item>
                                  </div>
                                </el-col>
                                <el-col :span="12">
                                  <div class="item">
                                    <el-form-item
                                      :prop="'tagConfig.tagList.' + index + '.tagList.' + index2 + '.operationValue'"
                                      :rules="[
                                        {
                                          required: true,
                                          message: '值不能为空',
                                          trigger: ['blur', 'change']
                                        }
                                      ]"
                                    >
                                      <factory-content-item :config="child"></factory-content-item>
                                    </el-form-item>
                                  </div>
                                </el-col>
                              </el-row>
                              <el-button
                                type="primary"
                                size="mini"
                                icon="el-icon-close"
                                circle
                                @click="deleteItem(index, index2)"
                              ></el-button>
                            </div>
                          </template>
                          <div class="ol space" v-else>
                            <!-- 第三层的逻辑符号 -->
                            <div class="logical" :class="{ 'logical-or': child.logicalOperation === 'or' }">
                              <el-form-item
                                :prop="'tagConfig.tagList.' + index + '.tagList.' + index2 + '.logicalOperation'"
                              >
                                <el-select
                                  v-model="child.logicalOperation"
                                  @click.native="toggleOperation(index, index2)"
                                  :level="index + '-' + index2"
                                  popper-class="factory-select"
                                  disabled
                                  class="default"
                                >
                                  <el-option label="且" value="and"></el-option>
                                  <el-option label="或" value="or"></el-option>
                                </el-select>
                              </el-form-item>
                            </div>
                            <div v-for="(third, index3) in child.tagList" :key="index3">
                              <div
                                class="list-item"
                                :level="3"
                                :fieldNm="third.fieldNm"
                                :index="index + '-' + index2 + '-' + index3"
                              >
                                <el-row :gutter="8">
                                  <el-col :span="8">
                                    <div
                                      class="item"
                                      align="center"
                                      draggable
                                      @dragstart="copyDrag($event, third, index, index2, index3)"
                                    >
                                      {{ third.fieldNm }}
                                    </div>
                                  </el-col>
                                  <el-col :span="4" align="center">
                                    <div class="item">
                                      <el-form-item
                                        :prop="
                                          'tagConfig.tagList.' +
                                            index +
                                            '.tagList.' +
                                            index2 +
                                            '.tagList.' +
                                            index3 +
                                            '.operationType'
                                        "
                                        :rules="[
                                          {
                                            required: true,
                                            message: '运算符不能为空',
                                            trigger: 'change'
                                          }
                                        ]"
                                      >
                                        <el-select v-model="third.operationType" @change="changeType($event, third)">
                                          <el-option label="---" value=""></el-option>
                                          <el-option
                                            v-for="opera in operatorType('type' + third.valueType)"
                                            :key="opera.value"
                                            :label="opera.key"
                                            :value="opera.value"
                                          ></el-option>
                                        </el-select>
                                      </el-form-item>
                                    </div>
                                  </el-col>
                                  <el-col :span="12">
                                    <div class="item">
                                      <el-form-item
                                        :prop="
                                          'tagConfig.tagList.' +
                                            index +
                                            '.tagList.' +
                                            index2 +
                                            '.tagList.' +
                                            index3 +
                                            '.operationValue'
                                        "
                                        :rules="[
                                          {
                                            required: true,
                                            message: '值不能为空',
                                            trigger: ['blur', 'change']
                                          }
                                        ]"
                                      >
                                        <factory-content-item :config="third"></factory-content-item>
                                      </el-form-item>
                                    </div>
                                  </el-col>
                                </el-row>
                                <el-button
                                  type="primary"
                                  size="mini"
                                  icon="el-icon-close"
                                  circle
                                  @click="deleteItem(index, index2, index3)"
                                ></el-button>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </template>
                  </div>
                </div>
              </div>
            </el-form>
          </div>
        </el-collapse-transition>
        <div class="section-title result-title">
          <i :class="showResult ? 'el-icon-caret-bottom' : 'el-icon-caret-right'" @click="showResult = !showCinfig"></i>
          结果预览
        </div>
        <el-collapse-transition>
          <div v-show="showResult">
            <devired-result :results="editForm.results"></devired-result>
          </div>
        </el-collapse-transition>
      </div>
    </div>
    <devired-drawer ref="deviredDrawer" @callback="confirm"></devired-drawer>
  </div>
</template>

<script>
import operator from '../../factory/operator'
import factoryContentItem from '../../factory/factory-content-item'
import deviredResult from './devired-result'
import deviredDrawer from './kpi-devired-drawer'
import bussunessConfig from '../bussiness/bussiness-config.js'
import cloneDeep from 'lodash/cloneDeep'
import { Promise } from 'q'
export default {
  components: {
    factoryContentItem,
    deviredResult,
    deviredDrawer
  },
  data() {
    return {
      loading: false,
      type: 'all',
      selectTable: '',
      tableList: [],
      fieldList: [],
      atomList: [],
      timeList: [],
      bussinessList: [],
      dimensionList: [],
      timeColumnList: [],
      showCinfig: true,
      showResult: false,
      oldConfig: {},
      keyword: '',
      editForm: {
        tagId: '',
        tagNm: '',
        tableNm: '',
        execFrequency: '',
        execTm: '',
        execWkList: [],
        execDtList: [],
        tagStory: '',
        valueType: '',
        results: [],
        atomicId: '',
        dimensionId: '',
        timeModifiersId: '',
        businessModifiersId: '',
        timeColumn: '',
        unitMeasure: '',
        businessType: 'quick',
        tagConfig: {
          logicalOperation: 'and',
          tagList: []
        }
      },
      editFormRules: {
        atomicId: [{ required: true, message: '原子指标不能为空', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getConfig(1, 'timeList')
    Promise.all([this.getTable(), this.getAtom()]).then(() => {
      if (this.$route.query.tagId) {
        this.editForm.tagId = this.$route.query.tagId
        this.getDetail()
      }
      if (this.$route.query.groupId) this.editForm.groupId = this.$route.query.groupId
    })
  },
  computed: {
    showFieldList() {
      return this.keyword.trim()
        ? this.fieldList.filter(item => item.fieldNm.indexOf(this.keyword.trim()) >= 0)
        : this.fieldList
    }
  },
  watch: {
    selectTable() {
      this.getFieldList()
    },
    'editForm.atomicId'() {
      this.editForm.dimensionId = ''
      this.editForm.businessModifiersId = ''
      this.editForm.timeColumn = ''
      this.keyword = ''
      this.getConfig(2, 'bussinessList')
      this.getConfig(3, 'dimensionList')
      this.getTimeColumn()
    }
  },
  methods: {
    getDetail() {
      this.$ajax({
        url: this.$ajax.setUrl(`IndexAllocation/getIndexDerivative/${this.editForm.tagId}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.editForm.tagNm = data.data.tagNm
          this.editForm.tableNm = data.data.tableNm
          this.editForm.execFrequency = data.data.execFrequency
          this.editForm.execTm = data.data.execTm
          this.editForm.execWkList = JSON.parse(data.data.execWkList)
          this.editForm.execDtList = JSON.parse(data.data.execDtList)
          this.editForm.tagStory = data.data.tagStory
          this.editForm.valueType = data.data.valueType
          this.editForm.results = JSON.parse(data.data.previewResults)
          this.editForm.atomicId = data.data.atomicId || ''
          this.editForm.timeModifiersId = data.data.timeModifiersId || ''
          this.editForm.unitMeasure = data.data.unitMeasure
          this.oldConfig = cloneDeep(this.editForm)
          this.showCinfig = false
          this.showResult = true
          this.$nextTick(() => {
            this.editForm.timeColumn = data.data.timeColumn
            this.editForm.dimensionId = data.data.dimensionId || ''
            if (data.data.businessModifiersId) {
              this.editForm.businessType = 'quick'
              this.editForm.businessModifiersId = data.data.businessModifiersId || ''
            } else {
              if (data.data.businessModifiersJson.length) {
                const config = JSON.parse(data.data.businessModifiersJson).tagConfig
                this.editForm.businessType = 'diy'
                this.editForm.businessModifiersName = data.data.businessModifiersName
                this.selectTable = config.request.labGrps.labs[0].labTbl
                  ? config.request.labGrps.labs[0].labTbl.split('.')[1]
                  : config.request.labGrps.labs[0].labs[0].labTbl
                  ? config.request.labGrps.labs[0].labs[0].labTbl.split('.')[1]
                  : config.request.labGrps.labs[0].labs[0].labs.labTbl.split('.'[1])
                this.editForm.tagConfig.logicalOperation = config.request.labGrps.logicTyp
                this.editForm.tagConfig.tagList = bussunessConfig.initLogic(config.request.labGrps.labs)
              }
            }
            this.changeAtom(this.editForm.atomicId)
          })
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    operatorType(key) {
      return operator[key]
    },
    changeType(type, item) {
      if (item.valueType == '4' || item.valueType == '5') {
        if (type === 'a<=x<b') item.operationValue = []
        else if (type === 8 || type === 9) item.operationValue = [1, '1']
        else item.operationValue = ''
      } else if (item.valueType == '6') {
        if (type === 'a<=x<b') item.operationValue = [1, 1]
        else item.operationValue = ''
      } else if (item.valueType == '7') {
        if (type === 'a<=x<b') item.operationValue = [1.0, 1.0]
        else item.operationValue = ''
      } else {
        item.operationValue = ''
      }
    },
    getTable() {
      return new Promise((resolve, reject) => {
        this.$ajax({
          url: this.$ajax.setUrl('der/derKpiType/getAllTable'),
          method: 'get',
          params: this.$ajax.setParams()
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.tableList = data.data
            resolve()
          } else {
            this.$message.error(data.data || data.msg)
            reject()
          }
        })
      })
    },
    getFieldList() {
      const tableItem = this.tableList.find(item => item.tableNm === this.selectTable)
      this.$ajax({
        url: this.$ajax.setUrl('der/derKpiType/getTableFields'),
        method: 'post',
        data: this.$ajax.setData({
          dbName: tableItem.dbName,
          plfmId: tableItem.plfmId,
          relaField: tableItem.relaField,
          tableNm: tableItem.tableNm,
          tableType: tableItem.tableType
        })
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.fieldList = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getAtom() {
      return new Promise((resolve, reject) => {
        this.$ajax({
          url: this.$ajax.setUrl('IndexAllocation/selectAtomicIndex'),
          method: 'get',
          params: this.$ajax.setParams()
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.atomList = data.data
            resolve()
          } else {
            reject()
          }
        })
      })
    },
    getTimeColumn() {
      this.$ajax({
        url: this.$ajax.setUrl(`IndexAllocation/selectTableToColumns/${this.editForm.atomicId}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.timeColumnList = data.data
        } else {
          // 失败后执行的操作
        }
      })
    },
    getConfig(type, listNm) {
      let url =
        type === 1
          ? `IndexAllocation/selectIndexConfig/${type}`
          : `IndexAllocation/selectIndexConfig/${type}/${this.editForm.atomicId}`
      this.$ajax({
        url: this.$ajax.setUrl(url),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this[listNm] = data.data
        } else {
          // 失败后执行的操作
        }
      })
    },
    changeAtom(atomicId) {
      const atomTarget = this.atomList.find(item => item.tagId === atomicId)
      this.selectTable = atomTarget.tableNm
    },
    showNm(item, fieldNm) {
      let config = JSON.parse(item.indexJson)
      return config[fieldNm]
    },
    addItem(item) {
      const target = this.tableList.find(table => table.tableNm === this.selectTable)
      this.editForm.tagConfig.tagList.push({
        tableNm: `${target.dbName}.${item.tableNm}`,
        fieldNm: item.fieldNm,
        valueType: item.valueType,
        datTyp: this.$dictDb('value_type')[item.valueType],
        operationType: '',
        operationValue: ''
      })
    },
    copyDrag(event, item, index = -1, index2 = -1, index3 = -1) {
      if (!item.fieldNm) return
      const target = this.tableList.find(table => table.tableNm === this.selectTable)
      event.dataTransfer.setData('tableNm', `${target.dbName}.${item.tableNm}`)
      event.dataTransfer.setData('fieldNm', item.fieldNm)
      event.dataTransfer.setData('valueType', item.valueType)
      event.dataTransfer.setData('datTyp', this.$dictDb('value_type')[item.valueType])
      event.dataTransfer.setData('operationType', item.operationType || '')
      event.dataTransfer.setData('operationValue', item.operationValue ? JSON.stringify(item.operationValue) : '')
      if (index >= 0) {
        event.dataTransfer.setData('config', JSON.stringify(Object.assign({}, item, { index, index2, index3 })))
        event.dataTransfer.setData('clientY', event.clientY)
      }
    },
    allowDrag(event) {
      event.preventDefault()
    },
    copyDrop(event) {
      // 判断拖动的高度小于50则不改变
      if (event.dataTransfer.getData('clientY')) {
        let clientY = event.dataTransfer.getData('clientY')
        if (Math.abs(event.clientY - clientY) < 50) return
      }
      let isConfig = event.dataTransfer.getData('config')
      event.preventDefault()
      let fieldNm = event.dataTransfer.getData('fieldNm')
      if (!fieldNm) return
      let content = this.editForm.tagConfig.tagList
      let tableNm = event.dataTransfer.getData('tableNm')
      let valueType = event.dataTransfer.getData('valueType')
      let datTyp = event.dataTransfer.getData('datTyp')
      let operationType = event.dataTransfer.getData('operationType')
      let operationValue = event.dataTransfer.getData('operationValue').length
        ? JSON.parse(event.dataTransfer.getData('operationValue'))
        : event.dataTransfer.getData('operationValue')
      let arg = {
        tableNm,
        fieldNm,
        valueType,
        datTyp,
        operationType,
        operationValue
      }
      if (
        this.editForm.tagConfig.tagList.length < 2 ||
        event.target.className.split(' ').find(item => item === 'list-wrap')
      ) {
        if (!this.editForm.tagConfig.tagList.length) this.editForm.tagConfig.logicalOperation = 'and'
        this.editForm.tagConfig.tagList.push(arg)
      } else {
        let nodes = []
        let target = event.target
        if (target.className.includes('el-input__inner')) {
          // 拖到逻辑条件处，直接添加
          const targetLevel = target.parentNode.parentNode.getAttribute('level')
          if (!targetLevel) this.editForm.tagConfig.tagList.push(arg)
          else if (targetLevel.indexOf('-') > -1) {
            // 第三层
            const level1 = targetLevel.split('-')[0]
            const level2 = targetLevel.split('-')[1]
            this.editForm.tagConfig.tagList[level1].tagList[level2].tagList.push(arg)
          } else {
            this.editForm.tagConfig.tagList[targetLevel].tagList.push(arg)
          }
        } else {
          while (target.className !== 'ul') {
            nodes.push(target)
            target = target.parentNode
          }
          const li = nodes.find(item => item.className === 'list-item')
          if (!li) return
          const targetLevel = parseInt(li.getAttribute('level'))
          const targetFieldNm = li.getAttribute('fieldNm')
          if (targetLevel === 1) {
            // 拖到第一层，一起掉到第二层
            const index = Number(li.getAttribute('index'))
            for (let i = 0; i < content.length; i++) {
              if (content[i].fieldNm === targetFieldNm && i === index) {
                const old_content = content[i]
                this.$set(content, i, {
                  logicalOperation: 'and',
                  tagList: [old_content, arg]
                })
              }
            }
          } else if (targetLevel === 2) {
            // 拖到第二层，一起掉到第三层
            const index = li.getAttribute('index')
            const index1 = index.split('-')[0]
            const index2 = index.split('-')[1]
            const old_content = content[index1].tagList[index2]
            this.$set(content[index1].tagList, index2, {
              logicalOperation: 'and',
              tagList: [old_content, arg]
            })
          } else {
            const index = li.getAttribute('index')
            const index1 = index.split('-')[0]
            const index2 = index.split('-')[1]
            const index3 = index.split('-')[2]
            content[index1].tagList[index2].tagList.splice(index3 + 1, 0, arg)
          }
        }
      }
      if (isConfig) {
        // 右侧拖动，删除原来的数据源
        let config = JSON.parse(isConfig)
        this.deleteItem(config.index, config.index2, config.index3)
        // 将子元素插入到原来图层
        if (config.derivedTag && config.derivedTag.tagList.length) {
          content.splice(config.index, 0, ...config.derivedTag.tagList)
        }
      }
      this.$forceUpdate()
    },
    deleteItem(index = -1, index2 = -1, index3 = -1) {
      if (index3 >= 0) {
        this.editForm.tagConfig.tagList[index].tagList[index2].tagList.splice(index3, 1)
        // 如果只剩一条，则提升到第二层
        if (this.editForm.tagConfig.tagList[index].tagList[index2].tagList.length < 2) {
          const content = this.editForm.tagConfig.tagList[index].tagList[index2].tagList[0]
          this.editForm.tagConfig.tagList[index].tagList.splice(index2, 1, content)
        }
      } else {
        if (index2 >= 0) {
          this.editForm.tagConfig.tagList[index].tagList.splice(index2, 1)
          // 如果只剩一条，则提升到第一层
          if (this.editForm.tagConfig.tagList[index].tagList.length < 2) {
            const content = this.editForm.tagConfig.tagList[index].tagList[0]
            this.editForm.tagConfig.tagList.splice(index, 1, content)
          }
        } else {
          this.editForm.tagConfig.tagList.splice(index, 1)
          // 如果只剩一条合并数据，则提升到第一层
          if (this.editForm.tagConfig.tagList.length && this.editForm.tagConfig.tagList.length < 2) {
            const content = this.editForm.tagConfig.tagList[0]
            if (!content.fieldNm) {
              this.editForm.tagConfig.logicalOperation = content.logicalOperation
              this.editForm.tagConfig.tagList = content.tagList
            }
          }
        }
      }
    },
    toggleOperation(index, index2 = -1) {
      if (index < 0) {
        this.editForm.tagConfig.logicalOperation = this.editForm.tagConfig.logicalOperation === 'and' ? 'or' : 'and'
      } else {
        if (index2 < 0) {
          const operation = this.editForm.tagConfig.tagList[index].logicalOperation
          this.editForm.tagConfig.tagList[index].logicalOperation = operation === 'and' ? 'or' : 'and'
        } else {
          const operation = this.editForm.tagConfig.tagList[index].tagList[index2].logicalOperation
          this.editForm.tagConfig.tagList[index].tagList[index2].logicalOperation = operation === 'and' ? 'or' : 'and'
        }
      }
    },
    handlePreview() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          let params = {
            atomicId: this.editForm.atomicId,
            businessModifiersId: '',
            businessModifiersName: this.editForm.businessModifiersName,
            dimensionId: this.editForm.dimensionId,
            timeModifiersId: this.editForm.timeModifiersId,
            timeColumn: this.editForm.timeColumn
          }
          if (this.editForm.businessType === 'quick') params.businessModifiersId = this.editForm.businessModifiersId
          else {
            if (this.editForm.tagConfig.tagList.length)
              params.businessModifiersJson = JSON.stringify({
                tagConfig: bussunessConfig.initParams(this.editForm.tagConfig)
              })
          }
          this.loading = true
          this.$ajax({
            url: this.$ajax.setUrl('IndexAllocation/showDerivedIndex'),
            method: 'post',
            data: this.$ajax.setData(params),
            timeout: 0
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.editForm.results = JSON.parse(data.data.previewResults)
              this.showCinfig = false
              this.showResult = true
              this.$message.success(data.msg)
              this.oldConfig = cloneDeep(this.editForm)
            } else {
              this.$message.error(data.data || data.msg)
            }
            this.loading = false
          })
        }
      })
    },
    handleSave() {
      if (!this.$utils.compareObject(this.editForm, this.oldConfig)) {
        this.$message.info('指标配置有变化，请先预览再保存！')
        return
      }
      const params = {
        tagId: this.editForm.tagId,
        tagNm: this.editForm.tagNm,
        execFrequency: this.editForm.execFrequency,
        execTm: this.editForm.execTm,
        execWkList: this.editForm.execWkList,
        execDtList: this.editForm.execDtList,
        tagStory: this.editForm.tagStory,
        valueType: this.editForm.valueType,
        dataLabs: this.editForm.dataLabs,
        results: this.editForm.results,
        atomicId: this.editForm.atomicId,
        businessModifiersId: '',
        businessModifiersName: this.editForm.businessModifiersName,
        dimensionId: this.editForm.dimensionId,
        timeModifiersId: this.editForm.timeModifiersId,
        timeColumn: this.editForm.timeColumn,
        unitMeasure: this.editForm.unitMeasure
      }
      if (this.editForm.groupId) params.groupId = this.editForm.groupId
      if (this.editForm.businessType === 'quick') params.businessModifiersId = this.editForm.businessModifiersId
      else {
        if (this.editForm.tagConfig.tagList.length)
          params.businessModifiersJson = JSON.stringify({
            tagConfig: bussunessConfig.initParams(this.editForm.tagConfig)
          })
      }
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.$refs.deviredDrawer.showDrawer(params)
        }
      })
    },
    confirm(params) {
      this.editForm.tagId = params.tagId
      this.editForm.tagNm = params.tagNm
      this.editForm.execFrequency = params.execFrequency
      this.editForm.execTm = params.execTm
      this.editForm.execWkList = params.execWkList
      this.editForm.execDtList = params.execDtList
      this.editForm.tagStory = params.tagStory
      this.editForm.valueType = params.valueType
      this.editForm.unitMeasure = params.unitMeasure
      this.oldConfig = cloneDeep(this.editForm)
      this.showCinfig = false
    },
    handleReject() {
      this.$confirm('确定取消最新的编辑？').then(() => {
        const config = cloneDeep(this.oldConfig)
        this.editForm.tagNm = config.tagNm
        this.editForm.tableNm = config.tableNm
        this.editForm.execFrequency = config.execFrequency
        this.editForm.execTm = config.execTm
        this.editForm.execWkList = config.execWkList
        this.editForm.execDtList = config.execDtList
        this.editForm.tagStory = config.tagStory
        this.editForm.valueType = config.valueType
        this.editForm.results = config.results
        this.editForm.atomicId = config.atomicId
        this.editForm.dimensionId = config.dimensionId
        this.editForm.timeModifiersId = config.timeModifiersId
        this.editForm.businessModifiersId = config.businessModifiersId
        this.editForm.timeColumn = config.timeColumn
        this.editForm.unitMeasure = config.unitMeasure
        this.editForm.businessType = config.businessType
        this.editForm.tagConfig = config.tagConfig
      })
    }
  }
}
</script>

<style lang="scss">
@import './kpi-devired.scss';
</style>
